#include "./sensor.h"
#include "../../device/gpio.h"

namespace driver {

using namespace device::gpio;

using PL = PB<3>;
using CP = PB<4>;
using Q7 = PB<5>;

Sensor::Sensor() {
    RCC->APB2ENR |= RCC_APB2ENR_IOPBEN;

    config_pp_out<PL, CP>();
    config_float_input<Q7>();
}

uint8_t Sensor::status() {
    using namespace utils;
    uint8_t v = read();
    return is_clr_bit<0>(v) |
        (is_clr_bit<1>(v) << 1) |
        (is_clr_bit<2>(v) << 2) |
        (is_clr_bit<3>(v) << 3) |
        (is_set_bit<4>(v) << 4);
}

uint8_t Sensor::read() {
    AUTO_LOCK(m_mutex);

    uint8_t val = 0;
    PL::clr();
    PL::set();

    for (uint8_t i = 0; i < 8; i ++) {
        val <<= 1;
        if (Q7::read()) {
            val ++;
        }
        CP::set();
        CP::clr();
    }
    return val;
}

}
